<script lang="ts">
  // 定义任务类型
  interface Task {
    id: number;
    title: string;
    completed: boolean;
    createdAt: string;
  }

  // 状态管理
  let tasks: Task[] = [];
  let newTaskTitle = '';
  let isLoading = true;
  let error = '';

  // 后端 API 地址
  const API_URL = 'http://localhost:3333/tasks';

  // 初始化：获取所有任务
  async function loadTasks() {
    try {
      const response = await fetch(API_URL);
      if (!response.ok) throw new Error('加载任务失败');
      tasks = await response.json();
      error = '';
    } catch (err) {
      error = err instanceof Error ? err.message : '未知错误';
    } finally {
      isLoading = false;
    }
  }

  // 创建新任务
  async function addTask() {
    if (!newTaskTitle.trim()) return;

    try {
      const response = await fetch(API_URL, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ title: newTaskTitle })
      });

      if (!response.ok) throw new Error('创建任务失败');
      
      const newTask = await response.json();
      tasks = [...tasks, newTask];
      newTaskTitle = ''; // 清空输入框
    } catch (err) {
      error = err instanceof Error ? err.message : '未知错误';
    }
  }

  // 切换任务完成状态
  async function toggleTask(id: number, currentState: boolean) {
    try {
      const response = await fetch(`${API_URL}/${id}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ completed: !currentState })
      });

      if (!response.ok) throw new Error('更新任务失败');
      
      // 更新本地列表
      tasks = tasks.map(task => 
        task.id === id ? { ...task, completed: !currentState } : task
      );
    } catch (err) {
      error = err instanceof Error ? err.message : '未知错误';
    }
  }

  // 删除任务
  async function deleteTask(id: number) {
    if (!confirm('确定要删除这个任务吗？')) return;

    try {
      const response = await fetch(`${API_URL}/${id}`, {
        method: 'DELETE'
      });

      if (!response.ok) throw new Error('删除任务失败');
      
      // 更新本地列表
      tasks = tasks.filter(task => task.id !== id);
    } catch (err) {
      error = err instanceof Error ? err.message : '未知错误';
    }
  }

  // 页面加载时获取任务
  loadTasks();
</script>

<div class="container">
  <h1>任务管理系统</h1>

  <!-- 错误提示 -->
  {#if error}
    <div class="error">{error}</div>
  {/if}

  <!-- 添加任务表单 -->
  <div class="add-task">
    <input
      type="text"
      bind:value={newTaskTitle}
      placeholder="输入新任务..."
      on:keydown={(e) => e.key === 'Enter' && addTask()}
    />
    <button on:click={addTask}>添加</button>
  </div>

  <!-- 任务列表 -->
  {#if isLoading}
    <p>加载中...</p>
  {:else if tasks.length === 0}
    <p>暂无任务，添加一个吧！</p>
  {:else}
    <ul class="task-list">
      {#each tasks as task (task.id)}
        <li class:completed={task.completed}>
          <input
            type="checkbox"
            checked={task.completed}
            on:change={() => toggleTask(task.id, task.completed)}
          />
          <span>{task.title}</span>
          <button class="delete-btn" on:click={() => deleteTask(task.id)}>删除</button>
        </li>
      {/each}
    </ul>
  {/if}
</div>

<style>
  .container {
    max-width: 800px;
    margin: 0 auto;
    padding: 20px;
    font-family: Arial, sans-serif;
  }

  h1 {
    color: #333;
    text-align: center;
  }

  .error {
    color: #dc3545;
    background: #f8d7da;
    padding: 10px;
    border-radius: 4px;
    margin-bottom: 15px;
  }

  .add-task {
    display: flex;
    gap: 10px;
    margin-bottom: 20px;
  }

  .add-task input {
    flex: 1;
    padding: 8px 12px;
    border: 1px solid #ddd;
    border-radius: 4px;
    font-size: 16px;
  }

  button {
    padding: 8px 16px;
    background: #007bff;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 16px;
  }

  button:hover {
    background: #0056b3;
  }

  .task-list {
    list-style: none;
    padding: 0;
    gap: 10px;
    display: flex;
    flex-direction: column;
  }

  .task-list li {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 12px;
    background: #f8f9fa;
    border-radius: 4px;
  }

  .task-list li.completed span {
    text-decoration: line-through;
    color: #6c757d;
  }

  .task-list li input[type="checkbox"] {
    width: 18px;
    height: 18px;
  }

  .task-list li span {
    flex: 1;
    font-size: 16px;
  }

  .delete-btn {
    background: #dc3545;
  }

  .delete-btn:hover {
    background: #bb2d3b;
  }
</style>
